/**
 * Copyright (c) 2025 by wuhensoft, All Rights Reserved.
 * Author: wuhensoft 4391728@qq.com
 * Date: 2025-06-03 11:34:20
 * LastEditors: wuhensoft
 * LastEditTime: 2025-06-19 13:55:44
 * FilePath: \Sources\Task\src\pwmb.c
 * Description:
 **/

#include "pwmb.h"
#include "i2c_ps.h"
#include "stdint.h"
#include "limits.h"
#include "mpu6050.h"
#include "STC32G_CAN.h"
#include "STC32G_EEPROM.h"
TaskHandle_t CanReceive_Handler;

/* CAN接收线程 */
portTASK_FUNCTION(CanReceiveTask, pvParameters)
{
	u8 sr;
	uint32_t NotifyValue;
	uint32_t Address_Temp;
	BaseType_t err;
	UNUSED(pvParameters);

	while (1)
	{
		err=xTaskNotifyWait((uint32_t	)0x00,				//进入函数的时候不清除任务bit
												(uint32_t	)ULONG_MAX,			//退出函数的时候清除所有的bit
												(uint32_t*	)&NotifyValue,		//保存任务通知值
												(TickType_t	)portMAX_DELAY);	//阻塞时间
		
		
		//printf("NotifyValue =  %d\r\n",NotifyValue);
		if(9527 == NotifyValue && CAN1_Rx[0].DLC == 3)
		{
			if(CAN1_Rx[0].DataBuffer[0] == 0x06 && CAN1_Rx[0].DataBuffer[1] == 0x05 && CAN1_Rx[0].DataBuffer[2] == 0x01)
			{
				MPU6050CaliFlag = 1;  
				printf("Init_MPU6050\r\n");
			}
			
			if(CAN1_Rx[0].DataBuffer[0] == 0xAD && CAN1_Rx[0].DataBuffer[1] == 0x05)
			{
				Address_Temp = 	((uint32_t)CAN1_Rx[0].DataBuffer[1] << 8) | CAN1_Rx[0].DataBuffer[2];
				
				Write_EEPROM_Data(FLASH_SLAVE_ADDRESS_ADDR,Address_Temp);
				
				EEPROM_read_n(FLASH_SLAVE_ADDRESS_ADDR,Read_Buffer,4);
				CAN1_Tx.ID = bytes_to_u32_be(Read_Buffer);
				CAN1_Tx.DLC = 3;             //数据长度
				CAN1_Tx.FF = STANDARD_FRAME;    //标准帧
				CAN1_Tx.RTR = 0;                //0：数据帧，1：远程帧
				CAN1_Tx.DataBuffer[0] = 0xAD;   //数据内容
				CAN1_Tx.DataBuffer[1] = CAN1_Tx.ID >> 8;
				CAN1_Tx.DataBuffer[2] = CAN1_Tx.ID;
	
				CANSEL = CAN1;		//选择CAN1模块

				CanSendMsg(&CAN1_Tx);   //发送一帧数据			
				
				printf("Slave_Address: %3X\r\n",CAN1_Tx.ID);
			}
			
		}
		//vTaskDelay(1);
	}

	vTaskDelete(NULL);
}
